import {
    goOut,
    changePsw,
    getMsgList,
    getMsgRead,
} from "@/api/api.js";
const speechSynthesis = window.speechSynthesis;
const speechSynthesisUtterance = new SpeechSynthesisUtterance();
export const initMsg = {
    data() {
        return {
            showLoading: false,
            name: "",
            pswlModal: false,
            modal: false,
            newp_w: "",
            newpsw: "",
            oldp_w: "",
            flag: "",
            msgFlag: false,
            timer: "",
            socket: null,
            porjectList: [],
            prjList: [],
            deptName: "",
            prjCode: "",
            deptId: "",
            drawer: false,
            msgPageNum: 1,
            pageSize: 10,
            msgList: [],
            totalCount: 0,
            msgCurrent: 1,
            isAdd: false,
            handleMachModal: false,
            GPSModal: false,
            handleSModal: false,
            MFlag: false,
            handleFseModal: false,
            handleEnvModal: false,
            handleFimModal: false,
            handleEmpModal: false,
            handleEquipModal: false,
            handleReportModal: false,
            handleSafetyReportModal: false,
            prjFlag: false,
            msgnavs: [{
                    name: "全部消息",
                    url: "/msg/all",
                    id: 0,
                },
                {
                    name: "未读消息",
                    url: "/msg/unread",
                    id: 1,
                },
                {
                    name: "已读消息",
                    url: "/msg/read",
                    id: 2,
                }

            ],
            cols: "#fff",
            prjimgFlag: true,
            lockReconnect: false,
            colors: [
                "#FA5C90 ",
                "#46D9FF ",
                "#4990FE ",
                "#856DFE ",
                "#FFC880 ",
                "#29b6f6 ",
                "#8bc34a",
                "#fbc02d",
                "#b3e5fc",
                "#ef5350",
                "#4dd0e1",
                "#304ffe",
                "#ff4081",
                "#82b1ff",
                "#6a1b9a",
                "#f57f17",
                "#b71c1c",
                "#a5d6a7",
                "#ffab91",
                "#880e4f",
                "#f8bbd0"
            ],
            fenceObjList: [],
            heartCheck: null,
        }
    },
    watch: {
        $route(to, from) {
            if (to.matched[0].path == "/msg") {
                localStorage.setItem("type", "");
                localStorage.setItem("type_sn", "")
                this.MFlag = false;
                this.$store.commit("setModalChildPage", this.msgnavs);
            } else {
                this.MFlag = true;
            }
            if (!(to.matched[0].path == "/inner")) {
                localStorage.setItem("type", "");
                localStorage.setItem("type_sn", "")
            }
        }
    },
    created() {
        let that = this;
        var heartCheck = {
            timeout: 30000, //每隔三十秒发送心跳
            timeoutObj: null,
            start: function() {
                var self = this;
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.timeoutObj = setInterval(function() {
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    //onmessage拿到返回的心跳就说明连接正常
                    console.log(that.socket.readyState);
                    //重新链接成功
                    if(that.socket.readyState == 1) {
                        console.log('ping')
                        that.socket.send("ping"); // 心跳包
                    }
                }, this.timeout)
            }
        }
        that.heartCheck = heartCheck;
        heartCheck = null;
    },
    methods: {
        // 语音播报的函数
        handleSpeak(text) {
            console.log(text)
            speechSynthesisUtterance.text = text;
            speechSynthesisUtterance.lang = "zh-CN";  // 使用的语言:中文
            speechSynthesisUtterance.volume = 1;      // 音量：1
            speechSynthesisUtterance.rate = 2;        // 语速：1
            speechSynthesisUtterance.pitch = 0;       // 音高：1
            speechSynthesis.speak(speechSynthesisUtterance);    // 播放
        },
        logout() {
            goOut()
                .then(res => {
                    if (res.code == 200) {
                        this.socket.close();
                        this.$router.push({ path: "/" });
                        this.$store.commit("setPorjectObject", {});
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        gopsw() {
            this.pswlModal = true;
            this.newp_w = "";
            this.newpsw = "";
            this.oldp_w = "";
        },
        submit() {
            if (this.newp_w === "" || this.newpsw === "" || this.oldp_w === "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "密码不能为空"
                });
                return;
            }
            if (this.newp_w !== this.newpsw) {
                this.$Modal.warning({
                    title: "密码错误",
                    content: "两次输入的密码不一致"
                });
                return;
            }
            let params = {
                oldPassword: this.oldp_w,
                newPassword: this.newp_w
            };
            changePsw(params)
                .then(res => {
                    if (res.code == 200) {
                        this.pswlModal = false;
                        this.modal = true;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        init() {
            let url;
            if (process.env.NODE_ENV === "development") {
                //开发环境
                url = this.$Global.socketTestSite
            } else if (process.env.NODE_ENV === "testing") {
                //测试环境
                url = this.$Global.socketTestSite
            } else if (process.env.NODE_ENV === "production") {
                //正式环境
                url = this.$Global.socketProSite
            }
            let wsUrl;
            if (window.location.protocol == "http:") {
                wsUrl = "ws://" + url + "/ms/api/ws/msg?userId=" + localStorage.getItem("userId");
            } else if (window.location.protocol == "https:") {
                wsUrl = "wss://" + url + "/ms/api/ws/msg?userId=" + localStorage.getItem("userId");
            }
            if (typeof WebSocket === "undefined") {
                alert("您的浏览器不支持socket");
            } else {
                // 实例化socket
                this.socket = new WebSocket(wsUrl);
                // 监听socket连接
                this.socket.onopen = this.open;
                // 监听socket错误信息
                this.socket.onerror = this.error;
                // 监听socket消息
                this.socket.onmessage = this.getMessage;
                //监听socket断开
                this.socket.onclose = this.getSocketClose;
            }
        },
        getMessage(e) {
            localStorage.setItem("msgFlag", 1);
            this.msgFlag = true;
            this.$notify.info({
                title: '消息',
                duration: 3000,
                message: '您收到一条最新消息，请到消息中心查看'
            });
            let data = JSON.parse(e.data);
            this.heartCheck.start();
            this.handleSpeak(data.title || '您收到一条最新消息，请到消息中心查看');
        },
        open() {
            if (this.socket.readyState == 1) {
                this.socket.send("ping");
            } else {
                this.reconnet();
            }
            this.heartCheck.start();
        },
        error: function() {
            this.open();
        },
        getSocketClose() {
            this.reconnet();
        },
        reconnet() {
            if (this.lockReconnect) {
                return;
            };
            this.lockReconnect = true;
            var tt;
            var _that = this
                //没连接上会一直重连，设置延迟避免请求过多
            tt && clearTimeout(tt);
            tt = setTimeout(function() {
                _that.open();
                _that.lockReconnect = false;
            }, 4000);
        },
        goIndex() {
            this.$router.push({ path: "/" });
        },
        getMore() {
            this.$router.push({ path: "/msg/all" });
            this.drawer = false;
        },
        getMsg() {
            this.drawer = true;
            localStorage.setItem("msgFlag", 2);
            this.msgFlag = false;
            this.getAllMsg();
        },
        getPrj() {
            this.prjFlag = !this.prjFlag
        },
        clickPrj() {
            this.prjFlag = true;
        },
        HiddenClick() {
            if (this.prjFlag) {
                this.prjFlag = false;
            }
        },
        //获取未读消息列表
        getAllMsg() {
            let parmas = {
                pageNum: this.msgPageNum,
                pageSize: this.pageSize,
                deptId: this.deptId,
                state: 0,
                moduleType: "",
                msgType: 1
            };
            getMsgList(parmas)
                .then(res => {
                    if (res.code == 200) {
                        this.msgList = res.data.list;
                        this.totalCount = res.data.total;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        pageChange(index) {
            this.msgPageNum = index;
            this.pageNumIndex = index;
            this.getAllMsg();
        },
        //消息详情
        getMsgDetails(item) {
            this.warnId = item.warnId;
            this.moduleType = item.moduleType;
            this.getRead([item.id]);
            //moduleType 1:设备报警详情 2:劳务报警详情 3:物质报警详情 4:环境报警详情 5:智能监控报警详情 6:特种设备报警详情 8:质量管理  9:安全管理
            if (item.moduleType == 1) {
                this.getMachDetails(item.warnId, true);
            } else if (item.moduleType == 6) {
                this.getFseDetails(item.warnId);
            } else if (item.moduleType == 4) {
                this.getEnvDetails(item.warnId);
            } else if (item.moduleType == 5) {
                this.getFimDetails(item.warnId);
            } else if (item.moduleType == 2) {
                this.getEmpDetails(item.warnId);
            } else if (item.moduleType == 7) {
                this.getEquipDetails(item.warnId, true);
            } else if (item.moduleType == 8) {
                this.getReportDetails(item.warnId, 8)
            } else if (item.moduleType == 9) {
                this.getReportDetails(item.warnId, 9)
            }
        },
        //将消息标记为已读
        getRead(list) {
            let parmas = {
                idList: list
            };
            getMsgRead(parmas)
                .then(res => {
                    if (res.code == 200) {} else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        //电子围栏报警区域
        searchGps() {
            var _that = this;
            _that.GPSModal = true;
            if (this.moduleType == 7) {
                let lng, lat, polygon, circle;
                let maplng, maplat
                if (this.fenceObjList[0].type == 1) {
                    //计算多边形中心点的坐标;
                    var polygonPointList = this.fenceObjList[0].polygonPointList;
                    var a = [];
                    var b = [];
                    for (let i in polygonPointList) {
                        a.push(polygonPointList[i].lat);
                        b.push(polygonPointList[i].lng);
                        //多边形的坐标点
                        let x = [polygonPointList[i].lng, polygonPointList[i].lat];
                    }
                    let latSum = 0;
                    for (let i in a) {
                        latSum += a[i];
                    }
                    maplat = latSum / a.length;
                    let lngSum = 0;
                    for (let i in b) {
                        lngSum += b[i];
                    }
                    maplng = lngSum / b.length;
                } else if (this.fenceObjList[0].type == 2) {
                    maplat = this.fenceObjList[0].centerPoint.lat;
                    maplng = this.fenceObjList[0].centerPoint.lng;
                }
                var machmap = new AMap.Map("container10", {
                    resizeEnable: true, //是否监控地图容器尺寸变化
                    zoom: 14, //初始化地图层级
                    center: [maplng, maplat], //初始化地图中心点
                    layers: [
                        // 卫星
                        new AMap.TileLayer.Satellite(),
                        // 路网
                        new AMap.TileLayer.RoadNet()
                    ]
                });
                this.fenceObjList.forEach((v, i) => {
                    if (v.type == 1) {
                        //计算多边形中心点的坐标;
                        let polygonPointList = v.polygonPointList;
                        let a = [];
                        let b = [];
                        let path = [];
                        for (let j in polygonPointList) {
                            //多边形的坐标点
                            let x = [polygonPointList[j].lng, polygonPointList[j].lat];
                            path.push(x);
                        }
                        polygon = new AMap.Polygon({
                            path: path,
                            strokeColor: this.colors[i],
                            strokeWeight: 6,
                            strokeOpacity: 0.5,
                            fillOpacity: 0.8,
                            fillColor: this.colors[i],
                            zIndex: 50
                        });
                        machmap.add(polygon);
                        // 缩放地图到合适的视野级别
                        machmap.setFitView([polygon])
                    } else if (v.type == 2) {
                        lat = v.centerPoint.lat;
                        lng = v.centerPoint.lng;
                        let radius = v.radius;
                        circle = new AMap.Circle({
                            center: [lng, lat],
                            radius: radius, //半径
                            borderWeight: 3,
                            strokeColor: this.colors[i],
                            strokeWeight: 6,
                            strokeOpacity: 0.5,
                            fillOpacity: 0.8,
                            strokeStyle: "dashed",
                            strokeDasharray: [10, 10],
                            // 线样式还支持 'dashed'
                            fillColor: this.colors[i],
                            zIndex: 50
                        });
                        circle.setMap(machmap);
                        // 缩放地图到合适的视野级别
                        machmap.setFitView([circle]);
                    }
                });
                var mouseTool = new AMap.MouseTool(machmap);
                // 构造官方卫星、路网图层
                var satelliteLayer = new AMap.TileLayer.Satellite();
                var roadNetLayer = new AMap.TileLayer.RoadNet();
                //添加图层
                machmap.add([satelliteLayer, roadNetLayer]);
            } else {
                if (_that.type == 1) {
                    var polygonPointList = _that.pointList;
                    var a = [];
                    var b = [];
                    var path = [];
                    for (let i in polygonPointList) {
                        a.push(polygonPointList[i].lat);
                        b.push(polygonPointList[i].lng);
                        //多边形的坐标点
                        let x = [polygonPointList[i].lng, polygonPointList[i].lat];
                        path.push(x);
                    }
                    let latSum = 0;
                    for (let i in a) {
                        latSum += a[i];
                    }
                    var lat = latSum / a.length;
                    let lngSum = 0;
                    for (let i in b) {
                        lngSum += b[i];
                    }
                    var lng = lngSum / b.length;
                    var polygon = new AMap.Polygon({
                        path: path,
                        strokeColor: "#ff00ff",
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillOpacity: 0.4,
                        fillColor: "#ff00ff",
                        zIndex: 50
                    });
                    var map = new AMap.Map("container10", {
                        zoom: 14,
                        center: [lng, lat]
                    });
                } else if (_that.type == 2) {
                    var lat = _that.centerPoint.lat;
                    var lng = _that.centerPoint.lng;
                    var radius = _that.radius;
                    var circle = new AMap.Circle({
                        center: [lng, lat],
                        radius: radius, //半径
                        borderWeight: 3,
                        strokeColor: "#ff00ff",
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillOpacity: 0.4,
                        strokeStyle: "dashed",
                        strokeDasharray: [10, 10],
                        // 线样式还支持 'dashed'
                        fillColor: "#ff00ff",
                        zIndex: 50
                    });
                    var map = new AMap.Map("container10", {
                        zoom: 14,
                        center: [lng, lat]
                    });
                }
                var mouseTool = new AMap.MouseTool(map);
                // 构造官方卫星、路网图层
                var satelliteLayer = new AMap.TileLayer.Satellite();
                var roadNetLayer = new AMap.TileLayer.RoadNet();
                //添加图层
                map.add([satelliteLayer, roadNetLayer]);
                if (_that.type == 1) {
                    map.add(polygon);
                    // 缩放地图到合适的视野级别
                    map.setFitView([polygon]);
                } else if (_that.type == 2) {
                    // circle.setMap(map);
                    map.add(circle);
                    // 缩放地图到合适的视野级别
                    map.setFitView([circle]);
                }
            }

        },
        //处理消息
        ok() {
            if (this.handleRemark == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请填写报警原因"
                });
                return;
            }
            if (this.handleResult == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请填写处理结果"
                });
                return;
            }
            this.handleSModal = true;
        },
        submithandle(moduleType) {
            let parmas;
            if (moduleType == 5) {
                parmas = {
                    resultId: this.warnId,
                    handleResult: this.handleResult,
                    handleRemark: this.handleRemark
                };
            } else {
                parmas = {
                    warnId: this.warnId,
                    handleResult: this.handleResult,
                    handleRemark: this.handleRemark
                };
            }
            //moduleType 1:设备报警处理 2:劳务报警处理 3:物质报警处理 4:环境报警处理 5:智能监控报警处理 6:特种设备报警处理
            if (moduleType == 1) {
                this.getMachHandle(parmas, 1);
            } else if (moduleType == 6) {
                this.getFseHandle(parmas, 1);
            } else if (moduleType == 4) {
                this.getEnvHandle(parmas, 1);
            } else if (moduleType == 5) {
                this.getFimHandle(parmas, 1);
            } else if (moduleType == 2) {
                this.getEmpHandle(parmas, 1);
            } else if (moduleType == 7) {
                this.getEquipHandle(parmas, 1)
            }
        }
    },
    mounted() {
        document.addEventListener("click", this.HiddenClick);
        if (localStorage.getItem("loginMethod") != "third-login") {
            this.init();
        }
        if (this.$route.path == "/msg/all" || this.$route.path == "/msg/unread" || this.$route.path == "/msg/read") {
            this.MFlag = false;
            this.$store.commit("setModalChildPage", this.msgnavs);
        } else {
            this.MFlag = true;
        }
        if ( this.$route.matched[0].meta.title == "导出记录" || this.$route.matched[0].meta.title == "旋挖设备" || this.$route.matched[0].meta.title == "车辆管理") {
            this.cols = "#9BA6A0";
            this.prjimgFlag = false;
        }
        if (this.$route.matched[0].meta.title == "人员管理" || this.$route.matched[0].meta.title == "进度管理" || this.$route.matched[0].meta.title == "文档管理") {
            this.cols = "#5E5F60";
            this.prjimgFlag = false;
        }
        if (this.$route.matched[0].path == "/lead") {
            this.cols = "#fff"
            this.prjimgFlag = true;
        }
        this.name = localStorage.getItem("username");
        this.flag = localStorage.getItem("zh_flag");
        if (localStorage.getItem("msgFlag") == 1) {
            this.msgFlag = true;
        } else {
            this.msgFlag = false;
        };
    },
    destroyed() {
        // 销毁监听
        if (this.socket) {
            this.socket.close();
        }
    },
}
